import { useState } from 'react';
import styles from './index.module.scss';
import { NavBar, TextArea, Toast } from 'antd-mobile';
import { useAppDispatch, useAppSelector } from '@/store';
import { getReplyCommentAction, sendCommentAction, sendCommentToCommentAction } from '@/store/action/comment';
import { getArticleDetailAction } from '@/store/action/article';
type Props = {
  // 评论的作者的名字
  // name?: string;
  onBack?: () => void;
};
export default function CommentInput({ onBack }: Props) {
  const [msg, setMsg] = useState('');
  const { articleDetail } = useAppSelector((state) => state.article);
  const { replyOriginData } = useAppSelector((state) => state.comment);
  //取出回复作者的名字
  const name = replyOriginData.aut_name;
  const dispatch = useAppDispatch();
  const handleSend = async () => {
    if (!msg.trim()) return Toast.show({ content: '请输入评论内容' });
    //通过是否存在名字区分
    if (name) {
      //发送对评论回复的接口
      await dispatch(
        sendCommentToCommentAction({ target: replyOriginData.com_id, content: msg, art_id: articleDetail.art_id })
      );
      //调用获取评论列表的接口
      dispatch(getReplyCommentAction(replyOriginData.com_id, 'c'));
    } else {
      //调用发送文章评论接口 //新评论追加到评论列表中去
      await dispatch(sendCommentAction({ target: articleDetail.art_id, content: msg }));
      //调用详情接口刷新评论数量
      await dispatch(getArticleDetailAction(articleDetail.art_id));
    }

    //关闭弹出层
    onBack && onBack();
    //提示用户
    Toast.show({ content: '评论成功' });
    //清空输入框
    setMsg('');
  };
  return (
    <div className={styles.root}>
      <NavBar
        onBack={onBack}
        right={
          <span className="publish" onClick={handleSend}>
            发表
          </span>
        }
      >
        {name ? '回复评论' : '评论文章'}
      </NavBar>
      <div className="input-area">
        {/* 回复别人的评论时显示：@某某 */}
        {name && <div className="at">@{name}:</div>}

        {/* 评论内容输入框 */}
        <TextArea value={msg} onChange={setMsg} placeholder="说点什么~" rows={10} />
      </div>
    </div>
  );
}
